package mine;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 
 * @author DQ
 * 软件2班 邓强
 */
public class MyMouseListener extends MouseAdapter{
	private MainGameUI game;
	private int size;
	
	public MyMouseListener(MainGameUI game) {
		this.game = game;
		size = game.size;
	}
	
	public void mouseClicked(MouseEvent e) {
		int row = (e.getY() - 50) / size;
		int col = (e.getX() - 4) / size;
		
		if (row * col < 0 || row > game.rows - 1 || col > game.cols - 1 ) {
			return;
		}
		
		if (e.getClickCount() == 2) {
			
		} else {
			if ( (game.mineMap[row][col] & 0b00000110) == 0b00000010) {
				return;
			}
			

				if (e.getButton() == 1) {
					if((game.mineMap[row][col] & 0b00000001) == 0b00000001) {
						game.isBomb = true;
					} else if( (game.mineMap[row][col] & 0b00000110) == 0b00000100) {
						return;
					} else {
						openWhiteOption(row, col);
					}
				} else if(e.getButton() == 2) {
					
				} else if(e.getButton() == 3) {
					if ( (game.mineMap[row][col] & 0b00000110 ) == 0b00000100 ) {
						game.mineMap[row][col] += 0b00000010;
					} else if( (game.mineMap[row][col] & 0b00000110 ) == 0b00000110 ) {
						game.mineMap[row][col] -= 0b00000110;
					} else {
						game.mineMap[row][col] += 0b00000100;
					}
				}
			}
			game.repaint();
		}

	private void openWhiteOption(int x, int y) {
		int state = game.mineMap[x][y];
		
		if ((state & 0b1) == 1 || (state & 0b110) == 0b010 || (state & 0b110) == 0b100 || (state & 0b110) == 0b110) {
			return;
		}
		
		game.mineMap[x][y] += 0b10;
		
		if ((state >>> 3) == 0) {
			if ( x - 1 >= 0 ) {
				openWhiteOption(x - 1, y);
				if ( y - 1 >= 0 ) {
					openWhiteOption(x - 1, y - 1);
				}
				
				if(y + 1 < game.cols) {
				openWhiteOption(x - 1, y + 1);
			}
		}
		
		if(x + 1 < game.rows) {
			openWhiteOption(x + 1, y);
			
			if (y - 1 >= 0) {
				openWhiteOption(x + 1, y - 1);
			}
			
			if (y + 1 < game.cols) {
				openWhiteOption(x + 1, y + 1);
			}
		}
		
		if (y - 1 >= 0) {
			openWhiteOption(x, y - 1);
		}
		
		if (y + 1 < game.cols) {
			openWhiteOption(x, y + 1);
		}
	}
}
}
